//
//  DBHomeViewController.swift
//  DBCA
//
//  Created by mugua on 2024/7/1.
//

import Foundation

class DBHomeViewController: DBBaseViewController, UITableViewDelegate, UITableViewDataSource {

    let disposeBag = DisposeBag()
    private var homeSectionDic = [Int: DBHomeSectionType]()
    private var dataArray: [DBHomePrickModel]?
    private var homeModel: DBHomeModel?
    private var applyModel: DBHomeApplyModel?
    
    private lazy var tableView: UITableView = {
        let tableView = UITableView(frame: CGRectZero, style: .plain)
        tableView.backgroundColor = .white
        tableView.delegate = self
        tableView.dataSource = self
        tableView.separatorStyle = .none
        tableView.showsVerticalScrollIndicator = false
        tableView.estimatedRowHeight = 50
        tableView.estimatedSectionHeaderHeight = 0
        tableView.estimatedSectionFooterHeight = 0
        tableView.tableFooterView = UIView()
        if #available(iOS 11.0, *) {
            tableView.contentInsetAdjustmentBehavior = .never
        } else {
            automaticallyAdjustsScrollViewInsets = false
        }
        
        tableView.setupRefreshHeader { [weak self] in
            self?.requestHomeData()
        }
        
        tableView.register(DBHomeLargeCardCell.self, forCellReuseIdentifier: DBHomeLargeCardCell.className())
        tableView.register(DBHomeSmallCardCell.self, forCellReuseIdentifier: DBHomeSmallCardCell.className())
        tableView.register(DBHomeRepayCell.self, forCellReuseIdentifier: DBHomeRepayCell.className())
        tableView.register(DBHomeFastLoanCell.self, forCellReuseIdentifier: DBHomeFastLoanCell.className())
        
        
        return tableView
    }()
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .red
        self.fd_prefersNavigationBarHidden = true
        
        initUI()
        
        requestHomeData()
        
        
        DBAlertView.showAlertView(type: .normal, title: "Apakah Anda yakin ingin mengabaikan verifikasi informasi ini?", message: "Menyelesaikan otentikasi akan meningkatkan peluang persetujuan pinjaman!", confirmBtnText: "确定", cancelBtnText: "取消") {
    
        } cancelBlock: {

        }
        
    }
    
    func initUI(){
        view.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.left.right.top.equalToSuperview()
            make.bottom.equalTo(-DBTabBarHeight)
        }
    }
    
    func requestHomeData() {
        let dic: [String: Any] = ["backshoot": DBRandomString()]
        DBToast.showLoading(text: nil, toView: DBKeyWindow)
        
        DBNetworkTool.request(method: .get, urlString: Home_URL, params: dic) { [weak self] baseModel in
            
            self?.tableView.mj_header?.endRefreshing()
            DBToast.hideFrom(view: DBKeyWindow)
            if baseModel.glared != 0 { return }
            if let signature = baseModel.signature as? [String: Any] {
                let homeModel = DBHomeModel(JSON: signature)
                self?.homeModel = homeModel
                self?.dataArray = homeModel?.prick
                self?.tableView.reloadData()
            }
            
        } failed: { [weak self] error in
            self?.tableView.mj_header?.endRefreshing()
            DBToast.hideFrom(view: DBKeyWindow)
        }
    }
    
    func requestApplyProductData(model: DBHomeWorkinModel) {
        
        requestApplyProductData1(model: model)
        
//        let loginVC = DBLoginViewController()
//        let loginNav = DBBaseNavigationController(rootViewController: loginVC)
//        loginNav.modalPresentationStyle = .fullScreen
//        DBNavigator.currentViewController()?.present(loginNav, animated: true)
        
//        DBURLRoute.checkUrl(url: "http://www.baidu.com" + "", toNativeFromVC: self)
        
        
        
    }
    
    func requestApplyProductData1(model: DBHomeWorkinModel) {
        
        let dic: [String: Any] = ["engage": "1001",
                                  "hope":"1000",
                                  "features":"1000",
                                  "obscene":model.pitched ?? "",
                                  "brow":DBRandomString()
        ]
        
        DBToast.showLoading(text: nil, toView: DBKeyWindow)
        
        DBNetworkTool.request(method: .post, urlString: Home_Apply_product, params: dic) { [weak self] baseModel in
            
            DBToast.hideFrom(view: DBKeyWindow)
            
            if baseModel.glared != 0 { return }
            guard let self = self else { return }
            
            guard let data = baseModel.signature as? [String: Any] else {
                return
            }
            
            self.applyModel = DBHomeApplyModel(JSON: data)
            if let alertModelArr = self.applyModel?.meant?.hundreds, alertModelArr.count > 0 {
                //
                DBLog("显示弹框")
            } else if let url = self.applyModel?.advice, url.count > 0 {
                DBLog("路由打开地址")
            } else {
                DBLog("跳转原生详情页")
            }
            
        } failed: { error in
            DBToast.hideFrom(view: DBKeyWindow)
        }

        
    }
    
    func createSectionData() -> Int {
        homeSectionDic.removeAll()
        var section = 0
        var currDataArr = [DBHomePrickModel]()
        let allType:[DBHomeSectionType] = [.DBHomeSectionType_Banner, .DBHomeSectionType_LargeCard, .DBHomeSectionType_SmallCard, .DBHomeSectionType_Repay, .DBHomeSectionType_ProductList]
        if let dataArray = dataArray {
            if dataArray.count > 0 {
                for subModel in dataArray {
                    if let colossal = subModel.colossal {
                        if allType.contains(colossal) {
                            homeSectionDic[section] = colossal
                            section = section + 1
                            currDataArr.append(subModel)
                        }
                    }
                }
                self.dataArray = currDataArr
            }
        }
        return section
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return createSectionData()
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        let sectionType = homeSectionDic[section]
        if sectionType == .DBHomeSectionType_ProductList {
            if let dataArray = dataArray {
                return dataArray[section].workin?.count ?? 0
            }
        }
        
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let sectionType = homeSectionDic[indexPath.section]
        switch sectionType {
        case .DBHomeSectionType_Banner: break
        case .DBHomeSectionType_LargeCard:
            let cell = DBHomeLargeCardCell(style: .default, reuseIdentifier: DBHomeLargeCardCell.className())
            let model = self.dataArray?[indexPath.section].workin?.first
            cell.model = model
            cell.buttonTap
                .subscribe(onNext: { [weak self] in
                    if let model = model {
                        self?.requestApplyProductData(model: model)
                    }
                })
                .disposed(by: disposeBag)
            return cell
        case .DBHomeSectionType_SmallCard:
            let cell = DBHomeSmallCardCell(style: .default, reuseIdentifier: DBHomeSmallCardCell.className())
            cell.model = self.dataArray?[indexPath.section].workin?.first
            cell.buttonTap
                .subscribe(onNext: { [weak self] in
                    DBLog("buttonTap")
                })
                .disposed(by: disposeBag)
            return cell
        case .DBHomeSectionType_Repay:
            let cell = DBHomeRepayCell(style: .default, reuseIdentifier: DBHomeRepayCell.className())
            cell.modelArr = self.dataArray?[indexPath.section].workin
            return cell
        case .DBHomeSectionType_ProductList:
            let cell = DBHomeFastLoanCell(style: .default, reuseIdentifier: DBHomeFastLoanCell.className())
            cell.model = self.dataArray?[indexPath.section].workin?[indexPath.row]
            cell.buttonTap
                .subscribe(onNext: { [weak self] in
                    DBLog("buttonTap")
                })
                .disposed(by: disposeBag)
            return cell
        case .none:
            break
        }
        return UITableViewCell(style: .default, reuseIdentifier: UITableViewCell.className())
    }
    
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        let sectionType = homeSectionDic[indexPath.section]
        switch sectionType {
        case .DBHomeSectionType_LargeCard:
            return 700
        case .DBHomeSectionType_SmallCard:
            return 400
        case .DBHomeSectionType_Repay:
            return 78
        case .DBHomeSectionType_ProductList:
            return 124
        case .DBHomeSectionType_Banner:
            return 0
        case .none:
            return 0
        }
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        let view = UIView()
        
        let label = UILabel()
        label.text = "Lebih Banyak Produk"
        label.textColor = DBTextColor
        label.font = DBFuturaMaxiStd_DemiFont(14)
        view.addSubview(label)
        label.snp.makeConstraints { make in
            make.left.equalTo(20)
            make.top.equalTo(15)
            make.height.equalTo(14)
        }
        
        return view
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        
        let sectionType = homeSectionDic[section]
        if sectionType == .DBHomeSectionType_ProductList {
            return 30
        }
        
        return 0
    }
    
}





